package com.spzx.common.rabbitmq.service;

import cn.hutool.core.lang.UUID;
import com.spzx.common.rabbitmq.configure.SpzxCorrelationData;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RabbitTemplate rabbitTemplate;
    public void sendMsg(String exchange ,String routingKey, Object message){
        sendMsg(exchange,routingKey,message,true,3,100);
    }
    public void sendMsg(String exchange ,String routingKey, Object message ,
                        boolean retry , int retryLimit , int timeIntervel){
        SpzxCorrelationData spzxCorrelationData = new SpzxCorrelationData();
        spzxCorrelationData.setId(UUID.fastUUID().toString());
        spzxCorrelationData.setExchange(exchange);
        spzxCorrelationData.setRoutingKey(routingKey);
        spzxCorrelationData.setMessage(message);
        spzxCorrelationData.setRetry(retry);
        spzxCorrelationData.setRetryLimit(retryLimit);
        spzxCorrelationData.setTimeIntervel(timeIntervel);
        spzxCorrelationData.setCount(1);
        //        System.out.println(spzxCorrelationData+" , id: "+ spzxCorrelationData.getId());
        //将spzxCorrelationData缓存到redis中使用id作为键  ，重试发送消息时 在两个回调中都可以获取它使用
        if(!retry){
            redisTemplate.opsForValue().set(spzxCorrelationData.getId() , spzxCorrelationData);
        }
        //生产者只负责将消息发送到交换机
        rabbitTemplate.convertAndSend(spzxCorrelationData.getExchange(),spzxCorrelationData.getRoutingKey(),
                                      spzxCorrelationData.getMessage()
                                      ,spzxCorrelationData);
    }
}